package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @author atguigu-mqx
 */
//@RestController
@Controller
@RequestMapping("/api/payment/alipay")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private PaymentService paymentService;


    //  http://api.gmall.com/api/payment/alipay/submit/{orderId}
    @RequestMapping("submit/{orderId}")
    @ResponseBody
    public String aliPay(@PathVariable Long orderId){
        String form = null;
        try {
            form = alipayService.createaliPay(orderId);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //  返回数据！
        return form;
    }

    //  同步回调的控制器！ 应该给用户回显一个可以看到的页面：提示用户继续购物.
    //  所有的页面都在web-all 中！
    @GetMapping("callback/return")
    public String callbackReturn(){
        //  重定向： http://payment.gmall.com/pay/success.html
        return "redirect:"+ AlipayConfig.return_order_url;
    }

    //  异步回调：http://vz4anh.natappfree.cc/api/payment/alipay/callback/notify
    //  http://vz4anh.natappfree.cc -> 127.0.0.1:80 会映射到网关！
    //  https: //商家网站通知地址?voucher_detail_list=[{"amount":"0.20","merchantContribute":"0.00","name":"5折券","otherContribute":"0.20","type":"ALIPAY_DISCOUNT_VOUCHER","voucherId":"2016101200073002586200003BQ4"}]&fund_bill_list=[{"amount":"0.80","fundChannel":"ALIPAYACCOUNT"},{"amount":"0.20","fundChannel":"MDISCOUNT"}]&subject=PC网站支付交易&trade_no=2016101221001004580200203978&gmt_create=2016-10-12 21:36:12&notify_type=trade_status_sync&total_amount=1.00&out_trade_no=mobile_rdm862016-10-12213600&invoice_amount=0.80&seller_id=2088201909970555&notify_time=2016-10-12 21:41:23&trade_status=TRADE_SUCCESS&gmt_payment=2016-10-12 21:37:19&receipt_amount=0.80&passback_params=passback_params123&buyer_id=2088102114562585&app_id=2016092101248425&notify_id=7676a2e1e4e737cff30015c4b7b55e3kh6& sign_type=RSA2&buyer_pay_amount=0.80&sign=***&point_amount=0.00
    //  http://localhost:8205/api/payment/alipay/callback/notify?out_trade_no=ATGUIGU1630139074028447&trade_status=TRADE_SUCCESS
    @PostMapping("callback/notify")
    @ResponseBody
    public String callbackNotify(@RequestParam Map<String,String> paramsMap,String outTradeNo,String status){
        System.out.println("死鬼，才回来.....");
        //  Map<String, String> paramsMap = ... //将异步通知中收到的所有参数都存放到map中
        boolean result = false; //调用SDK验证签名
        //        try {
        //            result = AlipaySignature.rsaCheckV1(paramsMap, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        //        } catch (AlipayApiException e) {
        //            e.printStackTrace();
        //        }

        //  获取到支付宝传递过来的out_trade_no , total_amount , app_id;
        //  String outTradeNo = paramsMap.get("out_trade_no");
        //        String appId = paramsMap.get("app_id");
        //        String totalAmount = paramsMap.get("total_amount");
        //  String status = paramsMap.get("trade_status");

        //  与 电商中的数据：orderInfo或者paymentInfo app_id;

        if(!result){
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            //  只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时，支付宝才会认定为买家付款成功。
            //  利用outTradeNo 查询交易记录
            //  select * from payment_info where out_trade_no = ? and payment_type = ?
            //  select * from payment_info where out_trade_no = ?
            PaymentInfo paymentInfoQuery = paymentService.getPaymentInfo(outTradeNo, PaymentType.ALIPAY.name());
            //  判断
            if (paymentInfoQuery==null){
                return "failure";
            }
            //  校验总金额
            //        BigDecimal totalAmountQuery = paymentInfoQuery.getTotalAmount();
            //        BigDecimal total = new BigDecimal(totalAmount);
            //        if (total.compareTo(totalAmountQuery)!=0){
            //            return "failure";
            //        }
            //        //  校验appId
            //        AlipayConfig alipayConfig = new AlipayConfig();
            //        if (!alipayConfig.getApp_id().equals(appId)) {
            //            return "failure";
            //        }
            if ("TRADE_SUCCESS".equals(status) || "TRADE_FINISHED".equals(status)){

                //  更新交易记录的状态！payment_status = PAID;
                paymentService.paySuccess(outTradeNo,PaymentType.ALIPAY.name(),paramsMap);
                return "success";
            }else {
                return "failure";
            }

        }else{
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            return "failure";
        }
    }

    //  退款接口：
    @RequestMapping("refund/{orderId}")
    @ResponseBody
    public Result refund(@PathVariable Long orderId){
        //  调用服务层方法
        Boolean flag = alipayService.refund(orderId);
        //  返回
        return  Result.ok(flag);
    }

    //  关闭支付宝交易
    //  http://localhost:8205/api/payment/alipay/closePay/{orderId}
    @GetMapping("closePay/{orderId}")
    @ResponseBody
    //  @GetMapping("closePay/{out_trade_no}")
    //  @GetMapping("closePay/{trade_no}")
    public Boolean closePay(@PathVariable Long orderId){
        //  返回
        Boolean flag = alipayService.closePay(orderId);
        return flag;
    }

    //  查看交易状态！
    @RequestMapping("checkPayment/{orderId}")
    @ResponseBody
    public Boolean checkPayment(@PathVariable Long orderId){
        Boolean flag = alipayService.checkPayment(orderId);
        return flag;
    }

    //  通过outTradeNo 来获取到PaymentInfo ：给取消订单业务使用！
    @GetMapping("getPaymentInfo/{outTradeNo}")
    @ResponseBody
    public PaymentInfo getPaymentInfo(@PathVariable String outTradeNo){
        //  调用服务层方法
        PaymentInfo paymentInfo = paymentService.getPaymentInfo(outTradeNo, PaymentType.ALIPAY.name());
        //  返回数据
        return paymentInfo;
    }

}
